﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.ScriptEngine.Custom;
using DWF.Studio.ScriptEngine.Implementation;
using DWF.Studio.ScriptEngine.IPC.Msg;
using DWF.Studio.Share.Log;
using DWF.Studio.Share.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace DWF.Studio.ScriptEngine
{
    /// <summary>
    /// 引擎启动器
    /// </summary>
    public static class EngineLauncher
    {
        public static void Launch(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                LogHelper.Error(e.ExceptionObject);
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                Custom.ExecutionContext.Instance?.Dispose();
            };

            string[] resolutionPaths = null;
            string[] assemblyNames = null;
            Dictionary<string, string> projectProperties = null;

            Tuple<string[], string[], Dictionary<string, string>> tuple_args = null;
            var arguments = ArgumentsHandler.Instance.GetArguments();
            ArgumentsHandler.Instance.Dispose();
            if (!String.IsNullOrWhiteSpace(arguments))
            {
                tuple_args = JsonHelper.Deserialize<Tuple<string[], string[], Dictionary<string, string>>>(arguments);

                resolutionPaths = tuple_args.Item1;
                assemblyNames = tuple_args.Item2;
                projectProperties = tuple_args.Item3;
            }

            string flag = null;
            if (args.Length > 0)
            {
                flag = args[0];
            }

            string pipename = null;
            if (args.Length > 1)
            {
                pipename = args[1];
            }

            string mainProcessId = null;
            if (args.Length > 2)
            {
                mainProcessId = args[2];
            }

            IScriptEngine scriptEngine = null;
            if (!String.IsNullOrWhiteSpace(flag))
            {
                Custom.ExecutionContext.Initialize(pipename, mainProcessId, resolutionPaths, projectProperties);
                switch (flag)
                {
                    case "WorkflowScriptEngine": scriptEngine = new WorkflowScriptEngine(Custom.ExecutionContext.Instance); break;
                    default: return;
                }
            }

            Custom.ExecutionContext.Instance?.Run();
            
            System.Environment.Exit(0);//防止有前台现在存在 进程无法退出
        }
    }
}
